package com.rt.cms.controller;

import com.rt.cms.common.Constants;
import com.rt.cms.common.base.Page;
import com.rt.cms.common.base.PageResultSet;
import com.rt.cms.common.base.Result;
import com.rt.cms.common.utils.SendMessageUtil;
import com.rt.cms.data.dto.company.ArchivesDto;
import com.rt.cms.data.entity.CompanyInfoBean;
import com.rt.cms.data.entity.TbApprovalRecord;
import com.rt.cms.data.entity.TbCompanyInfo;
import com.rt.cms.data.entity.TbCompayUploadInfo;
import com.rt.cms.data.entity.system.User;
import com.rt.cms.service.ArchivesService;
import com.rt.cms.service.CompanyInfoService;
import com.rt.cms.service.impl.CompanyInfoServiceImpl;
import com.rt.cms.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Create with IDEA
 *
 * @author Wangzs
 * @Description
 * @Date 2018/6/6
 * @Time 15:59
 */
@Controller
@RequestMapping("riskCheck")
public class RiskCheckController {

    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyInfoService companyInfoService;

    @RequestMapping(method = RequestMethod.GET)
    public String toPage(Model model) {
        return "archives/riskCheckList";
    }

    /**
     * 风控审核展示页面
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryByStatusRiskCheck")
    // @RequiresPermissions("user:view")
    public PageResultSet<ArchivesDto> queryByStatusRiskCheck(Page page, HttpServletRequest request, String comName,String riskStatus) {
        Integer status = Constants.Audit_Of_Wind;
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        int currentId = user.getId().intValue();
        List<User> userlist = userService.selectAllUserBypId(currentId);
        String ids = "";
        for (int i = 0; i < userlist.size(); i++) {
            if (i == 0) {
                ids = userlist.get(i).getId().toString();
            } else {
                ids = ids + "," + userlist.get(i).getId();
            }
        }
        return archivesService.findByStatus(status, page, ids, comName, currentId, "5",riskStatus);
    }

    /**
     * 分控审核操作
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkStatus", method = RequestMethod.POST)
    // @RequiresPermissions("user:view")
    public Result queryByStatusDepartCheck(String id,String operateType,String remark, HttpServletRequest request) {

        //更新状态
        TbCompanyInfo tbCompanyInfo = companyInfoService.getCompanyInfoById(Integer.valueOf(id));
        //记录操作记录
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        Date now = new Date();
        tbCompanyInfo.setFileOperateId(user.getId().intValue());
        TbApprovalRecord tbApprovalRecord = new TbApprovalRecord();
        tbApprovalRecord.setOperateId(user.getId().intValue());
        tbApprovalRecord.setOperateTime(now);
        tbApprovalRecord.setDemo(remark);
        if (Constants.Agree_Of_Wind == Integer.valueOf(operateType)) {
            tbCompanyInfo.setStatus(Constants.Wait_Online);
            tbCompanyInfo.setPassTime(now);
            tbApprovalRecord.setOperateType(Constants.Agree_Of_Wind);
            tbApprovalRecord.setStatus(Constants.Wait_Online);
            // 给A发短信
            try {
                String phone = userService.queryPhoneById(companyInfoService.getCompanyInfoById(tbCompanyInfo.getId()).getCheckOperateId());
                String str = Constants.Sms_RiskAgree_Head + tbCompanyInfo.getComName() + Constants.Sms_RiskAgree_End;
                SendMessageUtil.postUrl(str, Constants.Sms_URL, phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            tbCompanyInfo.setStatus(Constants.Audit_Of_Department);
            tbApprovalRecord.setOperateType(Constants.Refuse_Of_Wind);
            tbApprovalRecord.setStatus(Constants.Audit_Of_Department);
            //tbApprovalRecord.setDemo(remark);
            tbApprovalRecord.setIsRead(0);

            // 给B发短信
            String phone = userService.queryPhoneById(companyInfoService.getCompanyInfoById(tbCompanyInfo.getId()).getCheckOperateId());
            SendMessageUtil.postUrl(Constants.Sms_DepartmentOrRiskRefuse, Constants.Sms_URL, phone);
        }
        //修改企业信息
        if (companyInfoService.editCompanyInfo(tbCompanyInfo, tbApprovalRecord) > 0) {
            //map.put("message", "修改企业信息成功");
        } else {
            //map.put("message", "修改企业信息失败");
        }
        //保存图片信息
        try {
            uploadImage(request, tbCompanyInfo.getId());
        } catch (Exception e) {

        }

        System.out.print(tbCompanyInfo.getId());
        return Result.Success();
    }

    /**
     * 风控审核回显
     *
     * @param
     * @return
     */
    @RequestMapping("/detail")
    // @RequiresPermissions("user:view")
    public String detail(int id, Model model) {

        CompanyInfoBean companyInfoBean = companyInfoService.getCompanyInfoBeanById(id);

        CompanyInfoBean guaranteeCompanyInfoBean = new CompanyInfoBean();
        List<CompanyInfoBean> companyInfoBeans = companyInfoService.getGuaranteeCompanyInfoBean(id);
        /*if (companyInfoBeans.size() > 0) {
            guaranteeCompanyInfoBean = companyInfoBeans.get(0);
        }*/
        model.addAttribute("archives", companyInfoBean);

        model.addAttribute("archivesGuarantees", companyInfoBeans);
        return "archives/riskCheckDetail";
    }

    public Result uploadImage(HttpServletRequest request, int id) throws ServletException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();


        String message = "";
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);

        Iterator iter = multipartRequest.getFileMap().values().iterator();
        while (iter.hasNext()) {
            String oname = "";
            MultipartFile file = (MultipartFile) iter.next();
            String labelName = file.getName();
            if (!"".equals(file.getOriginalFilename())) {
                String curfilekzmstr = "";
                if (file.getOriginalFilename().lastIndexOf(".") > -1) {
                    curfilekzmstr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
                }
                oname = (int) ((Math.random() * 9 + 1) * 100000) + "" + (int) ((Math.random() * 9 + 1) * 100000) + curfilekzmstr;
                String outpath = Constants.realUrl   + oname;
                File newfile = new File(outpath);
                if (!newfile.getParentFile().exists()) {                //判断有没有父路径，就是判断文件整个路径是否存在
                    newfile.getParentFile().mkdirs();                //不存在就全部创建
                }
                FileOutputStream fos = new FileOutputStream(outpath);
                fos.write(file.getBytes());
                fos.close();
            }
            oname = Constants.showUrl+oname;
            message = saveFiles(id, labelName, oname);

        }

        map.put("message", message);
        return Result.Success();

    }

    private String saveFiles(int id, String labelName, String oname) {
        //文件存储
        String message = "";
        TbCompayUploadInfo tbCompayUploadInfo = new TbCompayUploadInfo();
        tbCompayUploadInfo.setComInfoId(id);
        tbCompayUploadInfo.setPicName(labelName);
        tbCompayUploadInfo.setPicUrl(oname);
        tbCompayUploadInfo.setIsDisplay(Constants.Display);
        if (companyInfoService.saveCompanyUploadInfo(tbCompayUploadInfo) > 0) {
            message = "文件上传成功";
        } else {
            message = "文件上传失败";
        }
        return message;
    }
}
